import { Form, Input, message, Modal } from 'antd';

import { FormInstance } from 'antd/lib/form';
import FormItem from 'antd/lib/form/FormItem';
import React from 'react';

import { SeatGroupInfo } from 'admin/schema/SeatGroup';
import { clearNull, verifyNull } from 'utils/tools';

import { addSeatGroup, modifySeatGroup } from '../../../../servers/servers';
import '../style.scss';

interface UserOperationProps {
  /**提交函数结束后的回调,编辑需要传obj，判断是否跳第一页 */
  callback: (obj?: any) => any;
}

interface UserOperationState extends UserOperationProps {
  /**抽屉是否弹出 */
  visible: boolean;
  /** 打开用途（新建/编辑） */
  mode: 'create' | 'modify';
}

export class SeatGroupOperation extends React.Component<UserOperationProps, UserOperationState> {
  /** 表单引用 */
  private formRef: React.RefObject<FormInstance>;

  /** 坐席组信息 */
  private FormData?: SeatGroupInfo;

  constructor(prop: UserOperationProps) {
    super(prop);
    this.formRef = React.createRef();
    this.FormData = undefined;
    this.state = {
      ...prop,
      visible: false,
      mode: 'create',
    };
  }

  componentDidMount() {}

  /**
   * 提交（新建/编辑）的数据
   */
  private submitData() {
    const form = this.formRef.current;
    form?.validateFields().then(res => {
      const val = form.getFieldsValue();
      if (this.state.mode === 'create') {
        addSeatGroup(
          clearNull({
            seatGroupName: val.seatGroupName,
          })
        )
          .then((res: any) => {
            message.success('新增成功');
            this.close();
            this.state.callback();
          })
          .catch((error: any) => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        modifySeatGroup(
          this.FormData?.seatGroupId as number,
          clearNull({
            seatGroupName: val.seatGroupName,
          })
        )
          .then((res: any) => {
            message.success('编辑成功');
            this.close();
            this.state.callback(this.FormData?.seatGroupId);
          })
          .catch((error: any) => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  }

  /**
   * 以新建/编辑的模式打开抽屉
   */
  public open(mode: 'create' | 'modify', data?: SeatGroupInfo) {
    this.setState(
      {
        visible: true,
        mode,
      },
      () => {
        if (mode === 'modify') {
          this.FormData = data;
          this.formRef.current?.setFieldsValue(data);
        }
      }
    );
  }

  /**
   * 关闭抽屉
   */
  public close() {
    this.setState({
      visible: false,
    });
    this.formRef.current?.resetFields();
  }

  render() {
    const { visible, mode } = this.state;

    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };

    return (
      <>
        {
          <Modal
            width={500}
            visible={visible}
            className="user-operation-drawer"
            title={mode === 'create' ? '新建坐席组' : '编辑坐席组'}
            onCancel={() => {
              this.close();
            }}
            onOk={() => {
              this.submitData();
            }}
          >
            <Form {...layout} layout="horizontal" ref={this.formRef}>
              <FormItem
                label="坐席组名称"
                name="seatGroupName"
                rules={verifyNull('请输入坐席组名称')}
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input maxLength={15} placeholder="请输入0-15位以内字符" />
              </FormItem>
            </Form>
          </Modal>
        }
      </>
    );
  }
}
